<template>
    <div>
        <van-nav-bar title="充值" left-text="返回" left-arrow @click-left="onClickLeft" />
    </div>
    <div>
        <van-form @submit="onSubmit">
            <van-field v-model="fieldValue" is-link readonly label="充值方式" placeholder="请选择充值方式"
                @click="showPicker = true" />
            <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker :columns=columns @cancel="showPicker = false" @confirm="onConfirm" />
            </van-popup>

            <van-field v-model="amount" name="pattern" placeholder="充值金额" style="width: 140px;"
                :rules="[{ pattern, message: '请输入正确内容' }]" />
            <!-- 优惠券单元格 -->
            <van-field v-model="selectedCount" is-link readonly :disabled="couponDisbale" label="选择优惠券" @click="showCouponList()" />
            <van-field v-model="selectedCount" is-link readonly :disabled="exchangeCodeDisable" label="使用兑换码" @click="useExchange()" />

            <!-- 优惠券列表 -->
            <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
                <div v-for="(userCouponInfo) in userCouponInfList" :key="userCouponInfo.id">
                    <div class="van-coupon-list-content">
                        <div class="van-coupon-list-head">
                            <h2 class="van-coupon-amount">
                                <span>{{ userCouponInfo.faceValueStr }}</span>
                            </h2>
                            <p class="van-coupon-condition">
                                {{ userCouponInfo.specialStr }}
                            </p>
                        </div>
                        <div class="van-coupon-list-body">
                            <p class="van-coupon-name">{{ userCouponInfo.name }}</p>
                            <p class="van-coupon-valid">2017.03.10 - 2017.12.30</p>
                        </div>
                        <div class="van-coupon-checkbox">
                            <van-checkbox-group v-model="checked" direction="horizontal">
                                <van-checkbox :name=userCouponInfo.id
                                    @click="checkbox(userCouponInfo.id)"></van-checkbox>
                            </van-checkbox-group>
                        </div>
                    </div>
                </div>
                <div style="display: flex; justify-content: center;align-items: center; margin-top: 16px;">
                    <van-button block type="primary" size="small" style="width: 160px;"
                        @click="onChange()">确定</van-button>
                </div>
            </van-popup>
            <van-popup  v-model:show="showExchangeCode" round position="bottom" style="height: 90%; padding-top: 4px;">
              <van-form @submit="onSubmitExchangeCode">
                <van-cell-group inset>
                  <van-field
                      v-model="exchangeCode"
                      name="exchangeCode"
                      label="兑换码"
                      placeholder="请输入兑换码"
                      :rules="[{ required: true, message: '请输入兑换码' }]"
                  />
                </van-cell-group>
                <div style="display: flex; justify-content: center;align-items: center; margin-top: 16px;">
                  <van-button block type="primary" size="small" style="width: 160px;" native-type="submit">
                    确定
                  </van-button>
                </div>
              </van-form>
            </van-popup>
            <van-cell-group v-show="couponAmountShow">
                <van-cell title="优惠金额" :value=couponAmount />
            </van-cell-group>
            <div style="display: flex; justify-content: center;align-items: center; margin-top: 16px;">
                <van-button block type="primary" size="small" style="width: 160px;" native-type="submit">
                    充值
                </van-button>
            </div>
          <div style="margin-left: 16px;margin-top: 5px; font-size: var(--van-cell-font-size);">
            <van-highlight keywords="温馨提示：" source-string="温馨提示：兑换码和优惠券不能同时使用" highlight-class="custom-class"/>
          </div>
        </van-form>
    </div>

</template>
<script setup>
import router from '@/router';
import { ref, onBeforeMount } from 'vue';
import { useRoute } from "vue-router";
import { showFailToast } from 'vant';
import { ChannelsList,Payment} from '@/api/pay.js';
import {CouponAmount, ExchangeCodeCheck, UserCouponList} from '@/api/market.js';
const checked = ref([]);

//路由信息
const route = useRoute();
//返回按钮事件
const onClickLeft = () => history.back();
//支付渠道
const columns = ref([])
//面值
const fieldValue = ref('');
//支付方式选择显示
const showPicker = ref(false);
//优惠金额显示
const couponAmountShow = ref(false);
//优惠金额
const couponAmount = ref('0.00');
//显示优惠券列表
const showList = ref(false);
const showExchangeCode=ref(false);
//选中的优惠券id
const selectedCouponIds = ref([]);
const selectedCount=ref('');
const channelId=ref('');

const exchangeCode=ref('');

const couponDisbale=ref(true);
const exchangeCodeDisable=ref(true);

const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;
    fieldValue.value = selectedOptions[0].text;
    channelId.value=selectedOptions[0].value;
};

const amount = ref('');

const chargingRecordId = ref('11');

const pattern = /^(?![0-9]{1,2}\.0$)([1-9]\d*(?:\.\d{1,2})?)$/;
const payment=ref({
    channelId:'',
    amount:'',
    exchangeCode:'',
    userCouponIdList:'',
    chargeRecordId:''
});

const exchangeCodeM=ref({
  amount:'',
  code:''
})
function onSubmit() {
    payment.value.amount=amount;
    payment.value.channelId=channelId;
    payment.value.userCouponIdList=selectedCouponIds;
    payment.value.exchangeCode=exchangeCode.value;
    Payment(payment.value)
    .then(res =>{
        if (res.data.code == 200000) {
            router.push({path: '/user/charge/money/doing', query: { outTradeNo: res.data.data } })
        }else{
            showFailToast(res.data.message);
        }
    })
}

onBeforeMount(() => {
    chargingRecordId.value = route.query.id;
    amount.value = route.query.amount
});
const queryM = ref({
    pageNum: 1,
    pageSize: 20,
    expireType: 0,
    status: 0
})

const userCouponInfList = ref([])
//获取当前用户可用优惠券
getUserCouponInf();
function getUserCouponInf() {
    userCouponInfList.value = [];
    queryM.value.expireType = 0;
    queryM.value.status=0;
    UserCouponList(queryM.value)
        .then(res => {
            if (res.data.code == 200000) {
                userCouponInfList.value = res.data.data.data
            } else {
                //错误提示框
            }
        })
}

const queryCounponAmount=ref({
    selectedCouponIds:[],
    amount:''
})

//确认选择优惠券按钮
function onChange() {
    queryCounponAmount.value.amount=amount;
    queryCounponAmount.value.selectedCouponIds=selectedCouponIds.value;
    if(selectedCouponIds.value.length>0){
        selectedCount.value='已选择'+selectedCouponIds.value.length+'张'
    }else{
        selectedCount.value=''
    }

    CouponAmount(queryCounponAmount.value)
        .then(res => {
            console.info(res.data)
            if (res.data.code == 200000) {
                couponAmount.value = res.data.data
                exchangeCodeDisable.value=false;
            } else {
                //错误提示框
                couponAmount.value=res.data.message
            }
        })
    showList.value = false;
    //调用后台计算出优惠总金额
    // couponAmount.value=100.99;
  couponAmountShow.value=true
}


function checkbox(couponId) {
    const isInArray = selectedCouponIds.value.includes(couponId);
    if (isInArray) {
        selectedCouponIds.value = selectedCouponIds.value.filter(id => id !== couponId);
    } else {
        selectedCouponIds.value.push(couponId);
    }
}

function showCouponList() {
  if(couponDisbale.value){
    if (amount.value === '' || amount.value === undefined) {
      showFailToast('请先填写金额');
    } else {
      showList.value = true;
    }
  }else {
    showFailToast('兑换码和优惠券不能同时使用')
  }


}
function useExchange() {
  if(exchangeCodeDisable.value){
    if (amount.value === '' || amount.value === undefined) {
      showFailToast('请先填写金额');
    } else {
      showExchangeCode.value = true;
    }
  }else {
    showFailToast('兑换码和优惠券不能同时使用')
  }


}

getChannelList()
function getChannelList() {
    ChannelsList()
        .then(res => {
            if (res.data.code === 200000) {
                columns.value = res.data.data
            } else {
                //错误提示框
            }
        })
}

const onSubmitExchangeCode = (values) => {
  if(couponAmount.value != '0.00'||Number(couponAmount.value) > 0){
    return ;
  }
  exchangeCodeM.value.code=values.exchangeCode;
  exchangeCodeM.value.amount=amount.value
  ExchangeCodeCheck(exchangeCodeM.value)
      .then(res => {
        if (res.data.code === 200000) {
          showExchangeCode.value = false;
          couponDisbale.value=false
          couponAmountShow.value = true
          couponAmount.value = res.data.data
          couponDisbale.value=false
        }else {
          showFailToast(res.data.message);
        }
      })
};

</script>
<style>
.van-cell__title {
    color: black;
}

.van-coupon-list {
    margin: var(--van-coupon-margin);
    background: var(--van-coupon-background);
    border-radius: var(--van-coupon-radius);
    box-shadow: var(--van-coupon-shadow);
    overflow: hidden;
}

.van-coupon-list-content {
    box-sizing: border-box;
    min-height: var(--van-coupon-content-height);
    padding: var(--van-coupon-content-padding);
    color: var(--van-coupon-content-text-color);
    align-items: center;
    display: flex;
    border-bottom: 1px solid black;
}

.van-coupon-list-head {
    min-width: var(--van-coupon-head-width);
    padding: 0 var(--van-padding-xs);
    color: var(--van-coupon-amount-color);
    text-align: center;
    position: relative;
}

.van-coupon-list-body {
    flex: 1;
    position: relative;
}

.van-coupon-amount {
    font-weight: var(--van-font-bold);
    font-size: var(--van-coupon-amount-font-size);
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 6px;
    overflow: hidden;
}

.van-coupon-condition {
    font-size: var(--van-font-size-sm);
    white-space: pre-wrap;
    line-height: 16px;
}

.van-coupon-name {
    font-weight: var(--van-font-bold);
    font-size: var(--van-coupon-name-font-size);
    line-height: var(--van-line-height-md);
    margin-bottom: 10px;
}

.van-coupon-valid {
    font-size: var(--van-font-size-sm);
}

.custom-class {
  color: red;
}
</style>